//
//  ___FILENAME___
//  ___PROJECTNAME___
//
//  Created by ___FULLUSERNAME___ on ___DATE___.
//___COPYRIGHT___
//

#import "___FILEBASENAMEASIDENTIFIER___.h"

#define kUpgradeCacheLastVersion    @"kUpgradeCacheLastVersion"

NSInteger ___VARIABLE_classPrefix:identifier___VersionNumber = ___PACKAGENAMEASIDENTIFIER____Version_1_0;

@interface ___VARIABLE_classPrefix:identifier___UpgradeVersionItem : NSObject

@property (nonatomic) NSInteger version;
@property (nonatomic) SEL method;

- (instancetype)initWithVersion:(NSInteger)version method:(SEL)method;

@end

@implementation ___VARIABLE_classPrefix:identifier___UpgradeVersionItem

- (instancetype)initWithVersion:(NSInteger)version method:(SEL)method
{
    if (self = [super init]) {
        self.version = version;
        self.method = method;
    }
    return self;
}

@end

@implementation ___FILEBASENAMEASIDENTIFIER___

+ (instancetype)sharedInstance
{
    static id instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = self.new;
    });
    return instance;
}

- (BOOL)needsUpgrade
{
    NSInteger lastVersion = [[NSUserDefaults standardUserDefaults] integerForKey:kUpgradeCacheLastVersion];
    return ___VARIABLE_classPrefix:identifier___VersionNumber != lastVersion;
}

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
- (void)upgrade
{
    NSInteger lastVersion = [[NSUserDefaults standardUserDefaults] integerForKey:kUpgradeCacheLastVersion];
    
    NSMutableArray *items = [NSMutableArray array];
    {
        [items addObject:[[___VARIABLE_classPrefix:identifier___UpgradeVersionItem alloc] initWithVersion:___PACKAGENAMEASIDENTIFIER____Version_1_0 method:@selector(upgrade10)]];
    }
    
    // code need change for every version.
    NSInteger version = lastVersion;
    for (___VARIABLE_classPrefix:identifier___UpgradeVersionItem *item in items) {
        if (item.version > version) {
            @try {
                [self performSelector:item.method];
            }
            @catch (NSException *exception) {
                LogDebug(@"upgrade %@ failed.", @(item.version));
                break;
            }
            version = item.version;
        }
    }
    
    [[NSUserDefaults standardUserDefaults] setInteger:version forKey:kUpgradeCacheLastVersion];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
#pragma clang diagnostic pop

#pragma mark - Upgrade Actions
- (void)upgrade10
{
    
}

@end
